/*
 * Title: 邮件传输代理的交互（The Letter Carrier's Rounds)
 * Author: Yuanshun L
 * Created : 14-otc-2021
 */


#include<cstdio>
#include<iostream>
#include<set>
#include<vector>
#include<map>
#include<string>
using namespace std;


// 将邮箱分割成mta名和用户名
void split_user_and_mta(const string &s, string &mta, string& user){
    int k = s.find('@');
    user = s.substr(0,k);
    mta = s.substr(k+1);

}

int main(){

    freopen("data.in","r",stdin);
    freopen("data.out","w",stdout);

    string mta,temp,user,mail,s; // mta名称
    int n; // 每个mta注册的用户数量
    set<string> db;

    while(cin>>s && s!="*"){
        cin >> mta >> n;
        // 遍历并保存用户
        while(n--){
            cin>>user;
            db.insert(user+"@"+mta);
        }
    }

    // 处理邮件
    while(cin >> s && s!="*"){
        string mta1,mta2,user1,user2;

        string sender = s;
        // 处理发件人
        split_user_and_mta(sender,mta1,user1);

        // 处理收件人
        map<string,vector<string> > reci;
        vector<string> mq; // 发送mta与多个不同接收mta交互的顺序
        set<string> list;
        while(cin >> s && s!="*"){
            split_user_and_mta(s,mta2,user2);

            if(list.count(s)) continue; // 去除重复收件人
            list.insert(s);

            // 增加新的接受mta
            if(!reci.count(mta2)){
                mq.push_back(mta2);
                reci[mta2] = vector<string>();
            }
            reci[mta2].push_back(s);
        }

        getline(cin,s); // 吃掉'*'后的换行符

        //作为测试
//        for(int i=0;i<mq.size();i++){
//            cout<<mq[i]<<endl;
//            for(int j=0;j<reci[mq[i]].size();j++){
//                cout<<reci[mq[i]][j]<<" ";
//            }
//            cout<<endl;
//        }

        // 邮件的内容
        string content;
        while(getline(cin,s) && s[0]!='*') content+="     " + s + "\n";

        // 发送mta和接收mta互动流程
        for(int i=0;i<mq.size();i++){
            mta2 = mq[i];
            cout<<"Connection between " << mta1  << " and " << mta2 << endl;
            cout<<"     "<< "HELO " << mta1 << endl;
            cout<<"     "<< "250" << endl;
            cout<<"     "<< "MAIL FROM:<" << sender<<">" << endl;
            cout<<"     "<< "250"<< endl;

            vector<string> users = reci[mta2];
            int size = users.size();
            bool ok = false;
            for(int j=0;j<size;j++){
                cout<<"     "<<"RCPT TO:<"<< users[j]<<">"<<endl;
                if(db.count(users[j])) {
                    ok = true;
                    cout<<"     "<<"250\n";
                }
                else cout<<"     "<<"550\n" ;
            }
            // 存在注册的邮箱的时候发送邮件内容
            if(ok){
                cout<<"     "<<"DATA\n""     "<<"354\n";
                cout<<content;
                cout<<"     "<<"250\n";
            }
            cout<<"     "<<"QUIT" << endl;
            cout<<"     "<<"221" << endl;
        }
    }
    return 0;
}
